package com.lkd.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VendoutData;
import com.lkd.contract.VendoutResultContract;
import com.lkd.emq.Topic;
import com.lkd.entity.ChannelEntity;
import com.lkd.entity.VendoutRunningEntity;
import com.lkd.service.ChannelService;
import com.lkd.service.VendoutRunningService;
import com.lkd.utils.JsonUtil;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Topic(TopicConfig.VMS_RESULT_TOPIC)
public class VendoutResultHandler implements MsgHandler {
    @Autowired
    private VendoutRunningService vendoutRunningService;
    @Autowired
    private ChannelService channelService;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void process(String jsonMsg) throws IOException {
        VendoutResultContract vendoutResultContract = JsonUtil.getByJson(jsonMsg, VendoutResultContract.class);
        boolean success = vendoutResultContract.isSuccess();
        VendoutData vendoutData = vendoutResultContract.getVendoutData();
        String innerCode = vendoutResultContract.getInnerCode();

        if (success){
            //获取出货记录表
            LambdaQueryWrapper<VendoutRunningEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(VendoutRunningEntity::getOrderNo, vendoutData.getOrderNo());
            VendoutRunningEntity vendoutRunningEntity = vendoutRunningService.getOne(queryWrapper);

            //如果出货成功则 将出货记录表（ tb_vendout_running）的status更改为true
            vendoutRunningEntity.setStatus(true);
            vendoutRunningService.updateById(vendoutRunningEntity);
        }else {
            ChannelEntity channelInfo = channelService.getChannelInfo(innerCode, vendoutData.getChannelCode());
            channelInfo.setCurrentCapacity(channelInfo.getCurrentCapacity()+1);
        }
        //释放分布式锁
        RLock lock = redissonClient.getLock(String.format(VMSystem.VM_LOCK_KEY_PREF, vendoutResultContract.getInnerCode()));
        lock.unlock();
    }
}
